package classes.multithread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : DuJiabao
 * @Date : 2021/2/9 17:50
 * @Project : java_learning
 * @File : null.java
 * @Desc :
 */
public class TryLockTest {

  SharedResource sr = new SharedResource();
  Runnable RunnableImpl = new Runnable() {
    @Override
    public void run() {
      int num = sr.getNum();
      sr.setNum(num + 1);
    }
  };


  public static void main(String[] args) {

  }
}

class SharedResource {
  private volatile int num = 0;
  private final Lock lock = new ReentrantLock();

  public int getNum() {
    lock.tryLock();
    try {
      lock.lock();
      return num;
    } finally {
      lock.unlock();
    }
  }

  public void setNum(int num) {
    lock.lock();
    this.num = num;
    lock.unlock();
  }
}
